#!/usr/bin/env python3
import os

# 基于文件的第一行注释，另存文件

def process_file(source_path):
    try:
        # 检查源文件是否存在
        if not os.path.exists(source_path):
            print(f"错误：文件 '{source_path}' 不存在")
            return
        
        # 读取源文件内容
        with open(source_path, 'r', encoding='utf-8') as f:
            # 读取第一行内容作为新文件名
            first_line = f.readline().strip()
            
            # 如果第一行是空的，使用默认名称
            if not first_line:
                new_filename = "default_filename.c"
                print("警告：文件第一行为空，使用默认文件名")
            else:
                # 去除开头的//
                if first_line.startswith('//'):
                    first_line = first_line[2:]  # 移除开头的//
                # 去除左右的空格
                first_line = first_line.strip()
                # 替换剩余空格为下划线，去除斜杠
                new_filename = first_line.replace(' ', '_')
                # 确保文件名以.c结尾
                if not new_filename.endswith('.c'):
                    new_filename += '.c'
        
        # 读取源文件全部内容
        with open(source_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 写入新文件
        with open(f"./gta/c/{new_filename}", 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"成功另存为新文件：{new_filename}")
        
    except Exception as e:
        print(f"处理文件时出错：{str(e)}")

if __name__ == "__main__":
    # 指定源文件路径
    source_file = "./gta/c/test.c"
    process_file(source_file)
    